<?php

class Post extends Eloquent {

    const TYPE_QUESTION = 'question';	//免费咨询
    const TYPE_GROUP_POST = 'group_post';	//微博动态
    const TYPE_DOC_AUDIT = 'doc_audit';
    const TYPE_LAWSUIT = 'lawsuit';
    const TYPE_PAY_TEXT = 'pay_text';	//图文咨询
    const TYPE_PAY_PHONE = 'pay_phone';	//电话咨询
    const TYPE_PAY_COMPANY = 'pay_company';	//小薇企服

    const STATUS_WAIT_PAY = 'wait_pay';       // 待付款（收费咨询）
    const STATUS_NEW = 'new';                 // （免费）刚刚创建，但是还没有被抢单		（收费）已付款，律师未受理
    const STATUS_REPLIED = 'replied';         // 已经有律师抢单的咨询，回复在进行中
    const STATUS_WAIT_FOR_EVALUATION = 'wait_for_evaluation';   // 已完成-未评价
    const STATUS_COMPLETE = 'complete';       // 咨询完成，用户已经评价
    const STATUS_CANCELLED = 'cancelled';     // 咨询取消
    const STATUS_REFUSED = 'refused';		  // （收费）律师已拒绝
    const STATUS_REMOVED = 'removed';		  // 咨询已被删除
	const STATUS_WAIT_FOR_CONFIRM	 = 'wait_for_confirm';

    const LAWYER_VISIBLE = 1;
    const LAWYER_UNVISIBLE = 0;
    const CUSTOMER_VISIBLE = 1;
    const CUSTOMER_UNVISIBLE = 0;

	const GOLD				=	2;
	const SILVER			=	1;
	const WHITE_GOLD		=	3;

    use SoftDeletingTrait;
    protected $dates = ['deleted_at'];
    protected $fillable = array('post_category', 'title', 'content', 'contact', 'province_id', 'city_id');

    public function save_comment(Comment $comment)
    {

       $output = DB::transaction(function() use($comment){

            $max_sequence_number = $this->comments()->lockForUpdate()->max('sequence_number') + 1;

            $comment->sequence_number = $max_sequence_number;

            $commentExtra = new CommentExtra();
            $commentExtra->likes_count = 0;

            $this->comments()->save($comment);
            $comment->commentExtra()->save($commentExtra);

            $this->postExtra()->increment('comments_count', 1, array(
                'last_comment_user_id' => $comment->creator_id
            ));
            $this->touch();
            $this->postExtra()->touch();
            $this->save();
			return $comment;
        });
		return $output;
    }

    public function assignToLawyer($lawyer_id)
    {
        $lawyer = Lawyer::find($lawyer_id);
        $lawyer->increment('case_count');
        $lawyer->save();
        PostThread::add($this->id, $lawyer_id);
    }

    public function assignToOrder($order_id)
    {
        PostOrder::add($this->id, $order_id);
    }

    public function comments()
    {
        return $this->hasMany('Comment')
            ->orderBy('created_at', 'ASC');
    }

    public function attachments()
    {
        return $this->hasMany('PostAttach')->select('post_id', 'type', 'src', 'file_name');
    }

    /**
     * 回复咨询的律师
     */
    public function commentators()
    {
        return $this->belongsToMany('User', 'post_thread');
    }

    /**
     * 这个用户是否咨询的回复者
     */
    public function isCommentator($user_id)
    {
        return (bool)$this->commentators()->where("post_thread.user_id", "=", $user_id)->count();
    }

    public function commentsCount() {
        return $this->comments()
            ->selectRaw('post_id, count(*) as aggregate')
            ->groupBy('post_id');
    }

    /**
     * 看看这个用户是否可以恢复这个咨询
     */
    public function canReply($user_id, $status=null) {
		$type = $this->type;
		if($type == self::TYPE_QUESTION){
			// 本人不能回复
			if ($this->creator_id == $user_id) {
				return false;
			}
			// 用户要是律师
			$user = User::find($user_id);
			if (!$user->isVerifiedLawyer()) {
				return false;
			}
			return true;
		}else {
			// 用户创建了咨询
			$userIsPostCreator = (bool)($this->creator_id == $user_id);
			if ($userIsPostCreator && !in_array($status, [self::STATUS_WAIT_FOR_EVALUATION, self::STATUS_COMPLETE])) {
				return true;
			}

			// 用户要是律师
			$user = User::find($user_id);
			if (!$user->isVerifiedLawyer() || in_array($status, [self::STATUS_WAIT_FOR_EVALUATION, self::STATUS_COMPLETE])) {
				return false;
			}

			// 用户要抢单成功
			return $this->isAssignedToLawyer($user_id);
		}
	}

	/**
     * 看看这个咨询是否被律师成功抢单
     */
    public function isAssignedToLawyer($user_id)
    {
        return (bool)PostThread::firstByAttributes(array('post_id' => $this->id, 'user_id' => $user_id));
    }

    public function scopeOfPostGroupId($query, $post_group_id)
    {
		if($post_group_id)
		{
			return $query->wherePostGroupId($post_group_id);
		}
    }

    public function scopeOfPostCategory($query, $post_category)
    {
        if ($post_category)
        {
			if(is_array($post_category))
			{
				$query = $query->whereIn('post_category', $post_category);
			} else {
				$query = $query->wherePostCategory($post_category);
			}
        }

        return $query;
    }

    public function scopeOfCityId($query, $city_id)
    {
        if ($city_id && $city_id != '990100')
        {
            $query = $query->whereCityId($city_id);
        }

        return $query;
    }

    public function scopeOfSearch($query, $search){
        if ($search)
        {
            $query = $query->where('title', 'like', "%$search%");
        }

        return $query;
    }

    public function scopeOfCreatedAt($query, $created_at) {
        if ($created_at)
        {
            $query = $query->where('created_at', '>=', $created_at);
        }
        return $query;
    }

    public function scopeOfCreatorId($query, $creator_id)
    {
        if ($creator_id)
        {
            $query = $query->whereCreatorId($creator_id);
        }

        return $query;
    }

    public static function getQuestions($post_category, $city_id, $search, $offset, $limit, $created_at = NULL, $order_by = 'created_at', $direction = 'DESC', $user_id = NULL, $status = [])
    {
       $query = Post::where('type', '=', self::TYPE_QUESTION)->OfCityId($city_id)->OfSearch($search)->OfPostCategory($post_category)->ofCreatorId($user_id)->ofCreatedAt($created_at);
        if($status){
        	$query = $query->whereIn('status', $status);
        }
        return $query->take($limit)->skip($offset)->orderBy($order_by, $direction)->get();
    }

    public static function getDocAudits($post_category, $city_id, $search, $offset, $limit, $order_by = 'created_at', $user_id = NULL)
    {
        return Post::where('type', '=', self::TYPE_DOC_AUDIT)->OfCityId($city_id)->OfSearch($search)->OfPostCategory($post_category)->ofCreatorId($user_id)->take($limit)->skip($offset)->orderBy($order_by, 'DESC')->get();
    }

    public static function getDocAuditsCount($post_category, $city_id, $search, $user_id = NULL)
    {
        return Post::where('type', '=', self::TYPE_DOC_AUDIT)->OfCityId($city_id)->OfSearch($search)->OfPostCategory($post_category)->ofCreatorId($user_id)->count();
    }

    public static function getQuestionsCount($post_category, $city_id, $search, $user_id = NULL)
    {
        return Post::where('type', '=', self::TYPE_QUESTION)->OfCityId($city_id)->OfSearch($search)->OfPostCategory($post_category)->ofCreatorId($user_id)->count();
    }

    public static function getGroupPosts($post_group_id, $offset, $limit, $order_by = 'created_at', $user_id = NULL)
    {
    	return Post::where('type', '=', self::TYPE_GROUP_POST)->OfPostGroupId($post_group_id)->ofCreatorId($user_id)->take($limit)->skip($offset)->orderBy($order_by, 'DESC')->get();
    }

    public static function getMicroblogPosts( $offset, $limit, $order_by = 'created_at',$user_id=NULL)
    {
    	$posts = Post::select('id', 'creator_id', 'content', 'parent_id', 'created_at')->where('type', '=', self::TYPE_GROUP_POST)->ofCreatorId($user_id)->take($limit)->skip($offset)->orderBy($order_by, 'DESC')->get();
    	//$posts = self::getPostExtras($posts);
      	return $posts;
    }
    public static function getFollowMicroblogPosts( $offset, $limit, $order_by = 'created_at',$user_id=array())
    {
    	return Post::where('type', '=', self::TYPE_GROUP_POST)->whereIn('creator_id',$user_id)->take($limit)->skip($offset)->orderBy($order_by, 'DESC')->get();

    }
    public static function getPostExtras($post_ids)
    {
    	return PostExtra::whereIn('post_id', $post_ids)->get();
    }

    public static function getGroupPostsCount($post_group_id, $user_id = NULL)
    {
        return Post::where('type', '=', self::TYPE_GROUP_POST)->OfPostGroupId($post_group_id)->ofCreatorId($user_id)->count();
    }



    public static function storeMicroblog($data)
    {
        return self::_storePost($data, self::TYPE_GROUP_POST, 0);
    }
    public static function storeQuestion($data)
    {
    	return self::_storePost($data, self::TYPE_QUESTION, 0);
    }

    public static function storePayQuestion($data)
    {
    	return self::_storePost($data, $data['type'], 0);
    }


    public static function storeDocAudit($data)
    {
        return self::_storePost($data, self::TYPE_DOC_AUDIT, 0);
    }

    private static function _storePost($data, $type, $post_group_id)
    {
		if(!isset($data['post_category']) ||empty($data['post_category']))$data['post_category']=0;
		if(!isset($data['parent_id']) ||empty($data['parent_id'])) $data['parent_id']=0;
        $post = new Post($data);
        $post->parent_id = $data['parent_id'];
        $post->content = $data['content'];
        $post->type = $type;
        $post->post_group_id = $post_group_id;
        $post->creator_id = Auth::check() ? Auth::user()->id : 0;
        $post->post_attachment_file_path = '';
        if($type == POST::TYPE_PAY_TEXT || $type == POST::TYPE_PAY_PHONE || $type == POST::TYPE_PAY_COMPANY){
        	$post->status = POST::STATUS_WAIT_PAY;
        } else {
            $post->status = POST::STATUS_NEW;
        }
        $postExtra = new PostExtra();
        $postExtra->views_count = 0;
        $postExtra->comments_count = 0;
        $postExtra->likes_count = 0;
        $postExtra->collects_count = 0;
	    $postExtra->last_comment_user_id = 0;

        $postAttachs = [];

        if(isset($data['file_paths']) && is_array($data['file_paths'])) {
        	$i = 0;
            foreach($data['file_paths'] as $file_path)
            {
                $postAttach = new PostAttach();
                $postAttach->src = $file_path;
                if(isset($data['file_names'][$i])){
                	$postAttach->file_name = $data['file_names'][$i];
                }
                $i++;
                $postAttachs[] = $postAttach;
            }
        }

        DB::transaction(function() use($post, $postExtra, $postAttachs){
            $post->save();
            $post->postExtra()->save($postExtra);
            foreach($postAttachs as $postAttach)
            {
                $postAttach->post_id = $post->id;
                $postAttach->save();
            }
			if($post->post_group_id)
			{
					$sns_group = SNSGroup::find($post->post_group_id);
					$sns_group->increment('post_count', 1);
					$sns_group->touch();
					$sns_group->save();
			}
        });

        return $post;
    }

    public static function getParentPost($posts)
    {
    	 foreach($posts as $post){
    	 	if($post->parent_id > 0){
    	 		$post->parent = Post::find($post->parent_id);
    	 		$post->parentImages=$post->getAttach();
    	 		$post->parentCreatorName = $post->parent->getUserinfo();
    	 	}
    	 }
    	 return $posts;
    }

    public function postExtra()
    {
        return $this->hasOne('PostExtra', 'post_id');
    }

    public function postAttach()
    {
    	return $this->hasMany('PostAttach', 'post_id');
    }


    public function creatorName()
    {
				if($this->creator_id)
				{
						$user = User::find($this->creator_id);
						$customer = Customer::where('user_id', $this->creator_id)->first();
						if ($customer)
						{
								return $customer->realname ? $customer->realname : $user->email;
						}
						$company = Company::where('user_id', $this->creator_id)->first();
						if ($company)
						{
								return $company->name ? $company->name : $user->email;
						}
						$lawyer = Lawyer::where('user_id', $this->creator_id)->first();
						if ($lawyer)
						{
								return $lawyer->realname ? $lawyer->realname.'律师' : $user->email;
						}

						return $user->email;
				} else {
						return $this->contact ? $this->contact : '游客';
				}
    }

    public function getUserinfo(){
		$user = User::find($this->creator_id);
		$data['name'] = $user->realname;
        $default= "img/lawyer_center_bgs/[]".rand(1,19).".png";
        $data['bg_img'] = UtilsHelper::getImage($user->bg_img, $default);
        $data['avatar'] = UtilsHelper::getImage($user->avatar, "img/dfimg.png");
        return $data;
    }

    //查询评论列表
    public function getComments($limit = PaginationHelper::FIRST_ROWS, $offset = 0, $order = 'created_at', $direction = 'DESC'){
    	$comments = Comment::where('post_id', $this->id)->take($limit)->skip($offset)->orderby($order, $direction)->get();
    	foreach( $comments as $comment ){
    		$comment->creator_name = $comment->creatorName();
    		$comment->creator_avatar = $comment->creatorAvatar();
    	}
    	return array_reverse($comments->toArray());
    }

    public function getAttach(){
    	$postAttachs = PostAttach::where('post_id', $this->id)->get();
    	foreach( $postAttachs as $postAttach ){

    		$postAttach->src = UtilsHelper::getImage($postAttach->src,null);
    	}
    	return $postAttachs;

    }


    public function creatorAvatar()
    {
        return $this->creator_id ? User::find($this->creator_id)->avatar : '';
    }

    public function creator()
    {
        $customer = Customer::where('user_id', $this->creator_id)->first();
        if ($customer)
        {
            return $customer;
        }

        $company = Company::where('user_id', $this->creator_id)->first();
        if ($company)
        {
            return $company;
        }

        $lawyer = Lawyer::where('user_id', $this->creator_id)->first();
        if ($lawyer)
        {
            return $lawyer;
        }

        return User::find($this->creator_id);
    }

		public static function getPostsByIDs($post_ids, $search = NULL)
		{
				return Post::whereIn('id', $post_ids)->OfSearch($search)->get();

		}

		public static function getPostByComments($search, $offset, $limit)
		{
			$user = Auth::user();
			if (! $user)
			{
				return;
			}

			$query = App::make('POST');

			if($search)
			{
				$query = $query->where('title', 'LIKE', "%$search%");
			}
			$query = $query->whereHas('Comments',function($q) use($user) {
						$q->where('creator_id', $user->id);
					});
			return $query->take($limit)->skip($offset)->orderBy('created_at', 'DESC')->get();
		}

		public function owner()
		{
			return $this->belongsTo('User','creator_id');
		}

		public static function getLawCase($id)
		{
		    return Post::where('type', Post::TYPE_DOC_AUDIT)->where('id', $id)->get();
		}

		public function getStatus(){
			switch ($this->status){
				case Post::STATUS_WAIT_PAY:
					return "待付款";
					break;
				case Post::STATUS_CANCELLED:
					return "已取消";
					break;
				case Post::STATUS_COMPLETE:
					return "已完成";
					break;
				case Post::STATUS_NEW:
					return "待受理";
					break;
				case Post::STATUS_REPLIED:
					return "待确认";
					break;
				case Post::STATUS_WAIT_FOR_EVALUATION:
					return "待评价";
					break;
			}
		}

		public function getType(){
			switch ($this->type)
			{
				case Post::TYPE_QUESTION:
					return "免费咨询";
					break;
				case Post::TYPE_PAY_PHONE:
					return "电话咨询";
					break;
				case Post::TYPE_PAY_TEXT:
					return "图文咨询";
					break;
				case Post::TYPE_PAY_COMPANY:
					return "法律服务";
					break;
			}
		}

		public function getPostCatKey(){
			if($this->post_category){
				return UtilsHelper::getWorkScopeName($this->post_category);
			}
		}

		public function getLawyerName(){
			$post_thread = PostThread::where('post_id', $this->id)->first();
			if($post_thread){
				$lawyerName = User::select('id', 'realname','avatar')->find($post_thread->user_id);
				$lawyerName->avatar = UtilsHelper::getImage($lawyerName->avatar, 'img/dfimg.png');
				return $lawyerName;
			}
			return;
		}

		public function getUserName(){
			$user = User::select('id', 'realname','avatar')->find($this->creator_id);
			$user->avatar = UtilsHelper::getImage($user->avatar, 'img/dfimg.png');
			return $user;
		}

		public function getAssignedLawyer() {
			$post_thread = PostThread::where('post_id', $this->id)->first();
			if($post_thread){
				$lawyer = User::find($post_thread->user_id);
				return $lawyer;
			}
			return null;
		}

// 		public function getLawyerName(){
// 			$post_thread = PostThread::where('post_id', $this->id)->first();
// 			if($post_thread){
// 				return $lawyerName = User::select('id', 'realname','avatar')->find($post_thread->user_id);
// 			}
// 			return;
// 		}

		public function getLawyerPhone(){
			$post_thread = PostThread::where('post_id', $this->id)->first();
			if($post_thread){
				return $lawyerName = User::find($post_thread->user_id)->phone;
			}
			return;
		}

		public function getOrder($id){
			$post_order = PostOrder::where('post_id', $id)->first();
			if($post_order){
				return Order::find($post_order->order_id);
			}
			return;
		}

    	public static function getUnreadCountForCreator($userId, $types, $status)
    	{
           return Post::where('creator_id', '=', $userId)
            ->whereIn('status', $status)
            ->whereIn('type', $types)
            ->where('is_read', '=', 0)
            ->count();
    	}

    	public static function getUnreadCountForAssignedLawyer($userId, $types, $status)
    	{
           return Post::join('post_thread', 'posts.id', '=', 'post_thread.post_id')
            ->where('post_thread.user_id', '=', $userId)
            ->whereIn('status', $status)
            ->whereIn('type', $types)
            ->where('is_read', '=', 0)
            ->count();
    	}

    	public static function readPost($id)
    	{
	        $post = Post::where('id', '=', $id)->lockForUpdate()->first();
	        if ($post->is_read)
	        {
	            return;
	        }
	        $post->is_read = 1;
	        $post->touch();
	        $post->save();
    	}

}